package com.example.mvplibrary.mvplibrary.presenter;

import com.example.mvplibrary.mvplibrary.model.BaseModel;
import com.example.mvplibrary.mvplibrary.view.BaseView;
import com.trello.rxlifecycle2.LifecycleProvider;

import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class BasePresenter<V extends BaseView,M extends BaseModel> implements RxPresenter<V> {
//    软引用:内存不足的时候，gC会回收
//    强引用: gc不会回收强引用的对象，及时内存不足，它宁愿内存溢出，也不回收
//    虚引用:相当于没有引用
    //内存不足时一定会触发gc
    //弱引用：gc触发到该垃圾对象，会立马对他进行回收
    private WeakReference<V>mWeakReference;
    public V mView;
    private M model;

    @Override
    public LifecycleProvider getLifecycleProvider() {
        if (getmView()!=null) {
            return (LifecycleProvider) mView;
        }
        return null;
    }

    public V getmView(){
        return mView;
    }

    public M getModel() {
        return model;
    }

    @Override
    public void bindView(V v) {
        mWeakReference=new WeakReference<V>(v);
        if (mWeakReference!=null){
            mView=mWeakReference.get();
        }
        initMode();
    }

    //利用反射动态创建model
    private void initMode() {
        ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
        Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
        Class<M> modelClass = (Class<M>) actualTypeArguments[1];
        try {
           model= modelClass.newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroyView() {
        if (mWeakReference!=null){
            mWeakReference.clear();
            mWeakReference=null;
        }
        if (mView!=null){
            mView=null;
        }
    }
}
